package com.lee.query;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.*;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

/**
 * @Description TODO
 * @Author winston
 * @DateTime 2022/3/10
 */
@SpringBootTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class RangeQuery {


    private static RestHighLevelClient client;
    private static ObjectMapper objectMapper;
    @BeforeAll
    public static void init() {
        client = new RestHighLevelClient(RestClient.builder(HttpHost.create("https://elasticsearch-dev.souban.io")));
        objectMapper = new ObjectMapper();
    }
    @AfterAll
    private static void destory() throws IOException {
        client.close();
    }

    @Test
    public void queryCombine() throws IOException {


        final RangeQueryBuilder age = QueryBuilders.rangeQuery("age");
        age.gte(10);
        age.lte(40);

        final SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(age);
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(10);
        final SearchRequest request = new SearchRequest();
        request.indices("user");
        request.source(searchSourceBuilder);
        final SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
        searchResponse.getHits().forEach(i -> System.out.println(i.getSourceAsString()));
    }
}
